package code;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




@WebServlet("*.Code")
public class CreateCode extends HttpServlet {
	

	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getServletPath();
		if("/show.Code".equals(path)) {
			createCode(request,response);
		}
		if("/prove.Code".equals(path)) {
			proveCode(request,response);
		}
	}
	
	protected void createCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Random random = new Random();
		BufferedImage image = new BufferedImage(70	, 30, BufferedImage.TYPE_INT_RGB);
		Graphics graphics = image.getGraphics();
		graphics.fillRect(0, 0, 70, 30);
		graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
		graphics.setFont(new Font("宋体", Font.BOLD, 18));
		String s = "qwertyuioplkjhgfdsazxcvbnm";
		StringBuffer code  = new StringBuffer();
		for(int i = 0;i<5;i++) {
			code.append(s.charAt(random.nextInt(s.length())));
		}
		graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
		graphics.drawString(code.toString(), 5, 20);
		
		for(int i = 0;i<3;i++) {
			graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
			graphics.drawLine(random.nextInt(70), random.nextInt(30), random.nextInt(70), random.nextInt(30));
		}
		
		
		request.getSession().setAttribute("code", code.toString());
		
		ImageIO.write(image, "jpg", response.getOutputStream());
	}
	protected void proveCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name =  request.getParameter("name");
		String code = request.getParameter("code");
		if("abc".equals(name)==true && code.equals(request.getSession().getAttribute("code"))) {
			response.sendRedirect(request.getContextPath()+"/202.jsp");
			request.getSession().removeAttribute("code");
			return;
		}
		
		request.setAttribute("message", "错误");
		request.getRequestDispatcher("/error.jsp").forward(request, response);
		
		
		
		
		
		
		
		
		
		
		
		
	}
}
